package com.sds.session.util;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.Cookie;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CookieUtil {
	
	private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);
	
	private CookieUtil() {}
	
	public static Cookie[] getCookieInstance(String cookieString) {
		if( cookieString==null || cookieString.trim().length()==0) return null;
		List<Cookie> cookieList = new ArrayList<Cookie>();
		
		StringTokenizer cookieTokenizer = new StringTokenizer(cookieString," ");
		
		while( cookieTokenizer.hasMoreTokens() ) {
			StringTokenizer cookieValueTokenizer = new StringTokenizer(cookieTokenizer.nextToken(), "=;");
			if( !cookieValueTokenizer.hasMoreTokens() ) continue;
			String key = cookieValueTokenizer.nextToken();
			if( "Path".equals(key) ) continue;
			String value = "";
			if( cookieValueTokenizer.hasMoreTokens() ) {
				value = cookieValueTokenizer.nextToken();
			}
			Cookie cookie = new Cookie(key, value);
			cookieList.add(cookie);
		}
		
		Cookie[] cookies = new Cookie[cookieList.size()];
		cookies = cookieList.toArray(cookies);
		
		return cookies;
	}
	
	public static String getCookieString(Cookie[] cookies) {
		if( cookies==null ) return "";
		String cookieString = "";
		for( Cookie cookie : cookies ) {
			cookieString += cookie.getName();
			if( cookie.getValue()!=null && !"".equals(cookie.getValue().trim()) ) {
				cookieString += "=" + cookie.getValue() + "; ";
			}
		}
		return cookieString;
	}
}
